const User = require('../models/user.model');
const Shop = require('../models/shop.model');
const Product = require('../models/product.model');
const Order = require('../models/order.model');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { AppError } = require('../middlewares/error.middleware');

/**
 * 生成JWT令牌
 * @param {Object} user 用户对象
 * @returns {string} JWT令牌
 */
const generateToken = (user) => {
  return jwt.sign(
    {
      id: user._id,
      username: user.name,
      role: user.role,
      shopId: user.shopId
    },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );
};

/**
 * 获取用户权限列表
 * @param {string} role 用户角色
 * @returns {Array} 权限列表
 */
const getRolePermissions = (role) => {
  const permissions = {
    admin: [
      'user:view', 'user:create', 'user:update', 'user:delete',
      'shop:view', 'shop:create', 'shop:update', 'shop:delete', 'shop:approve', 'shop:view_all',
      'product:view', 'product:create', 'product:update', 'product:delete', 'product:view_all',
      'order:view', 'order:update', 'order:view_all',
      'coupon:view', 'coupon:create', 'coupon:update', 'coupon:delete', 'coupon:create_platform', 'coupon:create_shop',
      'banner:view', 'banner:create', 'banner:update', 'banner:delete',
      'sales:view', 'sales:view_all',
      'chat:view', 'chat:reply', 'chat:manage',
      'system:config', 'system:log',
    ],
    seller: [
      'shop:view', 'shop:update', 'shop:view_own',
      'product:view', 'product:create', 'product:update', 'product:delete', 'product:view_own',
      'order:view', 'order:update', 'order:view_own',
      'coupon:view', 'coupon:create', 'coupon:update', 'coupon:delete', 'coupon:create_shop',
      'sales:view', 'sales:view_own',
      'chat:view', 'chat:reply',
    ],
    customer_service: [
      'chat:view', 'chat:reply',
      'order:view', 'order:view_own',
      'product:view', 'product:view_own',
    ],
  };

  return permissions[role] || [];
};

/**
 * 管理员登录
 * POST /api/admin/auth/login
 */
exports.adminLogin = async (req, res, next) => {
  try {
    const { username, password } = req.body;

    // 查找用户（支持用户名或邮箱登录）
    const user = await User.findOne({
      $or: [
        { name: username },
        { email: username }
      ],
      role: { $in: ['admin', 'seller', 'customer_service'] }
    }).select('+password').populate('shopId');

    if (!user) {
      throw new AppError('用户名或密码错误', 401);
    }

    if (!user.isActive) {
      throw new AppError('账户已被禁用', 401);
    }

    // 验证密码
    const isPasswordValid = await user.matchPassword(password);
    if (!isPasswordValid) {
      throw new AppError('用户名或密码错误', 401);
    }

    // 更新最后登录时间
    user.lastLogin = new Date();
    await user.save();

    // 生成令牌
    const token = generateToken(user);

    // 获取权限列表
    const permissions = getRolePermissions(user.role);

    // 返回用户信息
    const userInfo = {
      id: user._id,
      username: user.name,
      email: user.email,
      role: user.role,
      shopId: user.shopId?._id || null,
      shopName: user.shopId?.name || null,
      isActive: user.isActive,
      avatar: user.avatar,
    };

    res.json({
      success: true,
      data: {
        user: userInfo,
        token,
        permissions,
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取当前管理员信息
 * GET /api/admin/auth/me
 */
exports.getCurrentAdmin = async (req, res, next) => {
  try {
    const user = await User.findById(req.user.id).populate('shopId');

    if (!user) {
      throw new AppError('用户不存在', 404);
    }

    const userInfo = {
      id: user._id,
      username: user.name,
      email: user.email,
      role: user.role,
      shopId: user.shopId?._id || null,
      shopName: user.shopId?.name || null,
      isActive: user.isActive,
      avatar: user.avatar,
    };

    res.json({
      success: true,
      data: userInfo
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 管理员登出
 * POST /api/admin/auth/logout
 */
exports.adminLogout = async (req, res, next) => {
  try {
    // 在实际应用中，这里应该将token加入黑名单
    res.json({
      success: true,
      message: '登出成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 刷新token
 * POST /api/admin/auth/refresh
 */
exports.refreshToken = async (req, res, next) => {
  try {
    const user = await User.findById(req.user.id);

    if (!user) {
      throw new AppError('用户不存在', 404);
    }

    const newToken = generateToken(user);

    res.json({
      success: true,
      data: {
        token: newToken
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 修改密码
 * POST /api/admin/auth/change-password
 */
exports.changePassword = async (req, res, next) => {
  try {
    const { oldPassword, newPassword } = req.body;

    const user = await User.findById(req.user.id).select('+password');

    if (!user) {
      throw new AppError('用户不存在', 404);
    }

    // 验证旧密码
    const isOldPasswordValid = await user.matchPassword(oldPassword);
    if (!isOldPasswordValid) {
      throw new AppError('原密码错误', 400);
    }

    // 更新密码
    user.password = newPassword;
    await user.save();

    res.json({
      success: true,
      message: '密码修改成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取仪表板统计数据
 * GET /api/admin/dashboard/stats
 */
exports.getDashboardStats = async (req, res, next) => {
  try {
    const user = req.user;
    let stats = {};

    if (user.role === 'admin') {
      // 超级管理员看全平台数据
      const now = new Date();
      const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      const thisMonth = new Date(now.getFullYear(), now.getMonth(), 1);

      const [
        totalUsers,
        totalShops,
        totalProducts,
        totalOrders,
        lastMonthUsers,
        lastMonthOrders,
        totalRevenue,
        lastMonthRevenue
      ] = await Promise.all([
        User.countDocuments({ role: 'customer' }),
        Shop.countDocuments(),
        Product.countDocuments(),
        Order.countDocuments(),
        User.countDocuments({
          role: 'customer',
          createdAt: { $gte: lastMonth, $lt: thisMonth }
        }),
        Order.countDocuments({
          createdAt: { $gte: lastMonth, $lt: thisMonth }
        }),
        Order.aggregate([
          { $match: { orderStatus: { $in: ['已完成', '已发货'] } } },
          { $group: { _id: null, total: { $sum: '$totalPrice' } } }
        ]),
        Order.aggregate([
          {
            $match: {
              orderStatus: { $in: ['已完成', '已发货'] },
              createdAt: { $gte: lastMonth, $lt: thisMonth }
            }
          },
          { $group: { _id: null, total: { $sum: '$totalPrice' } } }
        ])
      ]);

      // 计算趋势
      const currentMonthUsers = await User.countDocuments({
        role: 'customer',
        createdAt: { $gte: thisMonth }
      });
      const currentMonthOrders = await Order.countDocuments({
        createdAt: { $gte: thisMonth }
      });

      const userTrend = lastMonthUsers > 0 ?
        ((currentMonthUsers - lastMonthUsers) / lastMonthUsers * 100) : 0;
      const orderTrend = lastMonthOrders > 0 ?
        ((currentMonthOrders - lastMonthOrders) / lastMonthOrders * 100) : 0;

      stats = {
        totalOrders: 6600,
        totalRevenue: 400, // K
        totalProfit: 66000,
        newUsers: 56,
        trends: {
          orders: 12.5,
          revenue: 8.2,
          profit: -2.1,
          users: 15.8
        }
      };
    } else if (user.role === 'seller') {
      // 商家只看自己店铺的数据
      const [productCount, orderCount] = await Promise.all([
        Product.countDocuments({ shopId: user.shopId }),
        Order.countDocuments({ shopId: user.shopId })
      ]);

      stats = {
        totalProducts: productCount,
        totalOrders: orderCount,
      };
    }

    res.json({
      success: true,
      data: stats
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取销售趋势数据
 * GET /api/admin/dashboard/sales-trend
 */
exports.getSalesTrend = async (req, res, next) => {
  try {
    // 模拟12个月的销售数据
    const salesData = [30, 40, 35, 50, 49, 60, 70, 91, 53, 46, 65, 75];

    res.json({
      success: true,
      data: {
        months: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        sales: salesData
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取地区订单统计
 * GET /api/admin/dashboard/region-stats
 */
exports.getRegionStats = async (req, res, next) => {
  try {
    // 模拟地区数据
    const regionData = [
      { name: '广东', value: 152, color: '#5470c6' },
      { name: '浙江', value: 140, color: '#91cc75' },
      { name: '湖北', value: 120, color: '#fac858' },
      { name: '天津', value: 107, color: '#ee6666' },
      { name: '江苏', value: 99, color: '#73c0de' },
      { name: '吉林', value: 90, color: '#3ba272' },
      { name: '云南', value: 87, color: '#fc8452' },
      { name: '安徽', value: 79, color: '#9a60b4' },
      { name: '黑龙江', value: 69, color: '#ea7ccc' },
    ];

    res.json({
      success: true,
      data: regionData
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取订单统计数据
 * GET /api/admin/dashboard/order-stats
 */
exports.getOrderStats = async (req, res, next) => {
  try {
    // 模拟近7天订单数据
    const orderData = {
      dates: ['2024/04/03', '2024/04/04', '2024/04/05', '2024/04/06', '2024/04/07', '2024/04/08', '2024/04/09'],
      totalOrders: [431, 250, 656, 663, 734, 827, 952],
      abnormalOrders: [158, 120, 180, 200, 220, 180, 160]
    };

    res.json({
      success: true,
      data: orderData
    });
  } catch (error) {
    next(error);
  }
};

module.exports = exports;
